import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getTags, createTag, updateTag, deleteTag } from '@/api/tags'
import { ElMessage } from 'element-plus'

export const useTagStore = defineStore('tag', () => {
  const tags = ref([])
  const loading = ref(false)

  // 获取所有标签
  async function fetchTags() {
    loading.value = true
    try {
      tags.value = await getTags()
    } catch (error) {
      ElMessage.error('获取标签列表失败')
    } finally {
      loading.value = false
    }
  }

  // 创建标签
  async function addTag(tagData) {
    try {
      const tag = await createTag(tagData)
      tags.value.push(tag)
      ElMessage.success('标签创建成功')
      return tag
    } catch (error) {
      ElMessage.error('创建标签失败')
      throw error
    }
  }

  // 更新标签
  async function modifyTag(id, tagData) {
    try {
      const tag = await updateTag(id, tagData)
      const index = tags.value.findIndex(t => t.id === id)
      if (index !== -1) {
        tags.value[index] = tag
      }
      ElMessage.success('标签更新成功')
      return tag
    } catch (error) {
      ElMessage.error('更新标签失败')
      throw error
    }
  }

  // 删除标签
  async function removeTag(id) {
    try {
      await deleteTag(id)
      tags.value = tags.value.filter(t => t.id !== id)
      ElMessage.success('标签已删除')
    } catch (error) {
      ElMessage.error('删除标签失败')
      throw error
    }
  }

  return {
    tags,
    loading,
    fetchTags,
    addTag,
    modifyTag,
    removeTag
  }
})

